package bg.consulting.labo.util;

import javax.media.Controller;
import javax.media.ControllerClosedEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.Format;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.Processor;
import javax.media.control.FormatControl;
import javax.media.protocol.DataSource;


public class UtilJMF {

	public static void waitUntilRealize(Player p) {
		waitUntil(p, Player.Realized);
	}

	public static void waitUntil(Player p, int state) {
		if (p== null){
			return;
		}
		System.out.println("waitUntil : "+getStateLabel(state)+"  : state now: "+p.getState()+"  ");
		try {
			while (p.getState() < state)
				Thread.sleep(100);
		} catch (InterruptedException eX) {
		} catch (Exception eX) {
			eX.printStackTrace();
		}
	}

	public static String getProcessorState(Controller processor) {
		int state = processor.getState();
		String r = "";		
		return state + " " + getStateLabel(state);
	}
	
	public static String getStateLabel(int state) {
		String r = "??";
		if (state == 300) {
			r = "REALIZED";
		} else if (state == 400) {
			r = "PREFETCHING";
		} else if (state == 500) {
			r = "PREFETCHED";
		} else if (state == 600) {
			r = "STARTED";
		}
		return state + " " + r;
	}


	public static Format getFormat(DataSource dataSource) {
		Format format = null;
		try {
			FormatControl fc = (FormatControl) dataSource.getControl(FormatControl.class.getName());
			System.out.println("getFormat.formatControl:  " + fc);
			if (fc == null) {
			} else {
				format = fc.getFormat();
			}			
		} catch (Exception e) {			
			e.printStackTrace();			
		}
		System.out.println("getFormat from : "+getLocatorURLName(dataSource)+"  format:" + format);
		return format;
	}
	
	public static String getLocatorURLName(DataSource dataSource){
		String r = "?";
		try {
			MediaLocator locator = dataSource.getLocator();
			if (locator == null){				
			}else {
				r = locator.getRemainder();
			}
			return r;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return r;
	}
	
	public static void waitUntil(Player p, int state, int timeMax) throws Exception {
		System.out.println("waitUnil "+getStateLabel(state)+"  : state now: "+p.getState()+"  ");
		long timeNow = System.currentTimeMillis();
		boolean isOn = true;
		try {
			while (isOn ){
				if ((p.getState() >=state)){
					return ;
				}
				if (( System.currentTimeMillis() > timeNow+timeMax)){
					System.out.println("waitUnil "+getStateLabel(state)+"  : state now: "+p.getState()+"  ");
					throw new Exception("waitUnti state:"+state+" timeMax "+timeMax+"  TIME OUT");
				}
			}
		} catch (Exception eX) {
			eX.printStackTrace();
		}
		return ;
	}


}
